<template>
  <div>
    <Tablefilter :filter="filterModel" @search="search" @del="delProduct()" @add="editProduct()"></Tablefilter>

    <commonTable
      :getTableList="getTableList()"
      :refresh.sync="refresh"
      :filter="filter"
      :selectRow.sync="selectRow"
      :columns="columns"
    ></commonTable>
    <el-dialog
      :title="productForm.productId ? $t('common.edit'):$t('common.add')"
      :visible.sync="editDialog"
      :before-close="cancelEdit"
      width="700px"
      lock-scroll
      center
    >
      <el-form
        ref="productForm"
        :model="productForm"
        label-width="100px"
        :hide-required-asterisk="true"
        label-position="left"
      >
        <el-form-item
          v-for="item,key in productForm"
          :label="$t('product.'+key)"
          :rules="productFormRules[key]"
          :prop="key"
          v-if="key !== 'productId'"
        >
          <span slot="label">
            <i class="required" :class="{'required-hide':key==='productAttr'}"></i>
            {{$t('product.'+key)}}
          </span>
          <upload-img
            ref="uploadImg"
            v-if="key === 'productImg'"
            :upload-list="uploadList"
            :length="1"
            style="display: inline-block"
          ></upload-img>

          <el-select v-else-if="key === 'countryId'" v-model="productForm[key]">
            <el-option
              v-for="option in countryOptions"
              :key="option.value"
              :label="$t('option.'+option.label).indexOf('.')>-1?option.label:$t('option.'+option.label)"
              :value="option.value"
            ></el-option>
          </el-select>
          <el-select v-else-if="key === 'productType'" v-model="productForm[key]">
            <el-option
              v-for="option in productTypeOptions"
              :key="option.value"
              :label="$t('option.'+option.label).indexOf('.')>-1?option.label:$t('option.'+option.label)"
              :value="option.value"
            ></el-option>
          </el-select>
          <el-input
            v-else
            v-model="productForm[key]"
            :placeholder="key ==='productAttr'? $t('product.productAttrTipDetail'):''"
            :rows="key ==='productAttr'? 3:1"
            :type="key ==='productAttr'?'textarea':'text'"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('product.productAttr')">
          <span slot="label" :style="{marginLeft: '10px'}">{{$t('product.productAttr')}}</span>
          <el-row>
            <el-col :sm="4">
              <div>属性名称</div>
            </el-col>
            <el-col :sm="4" :offset="1">
              <div>属性值</div>
            </el-col>
            <el-col :sm="4" :offset="1">
              <div>图片预览</div>
            </el-col>
            <el-col :sm="4">
              <div>&nbsp;</div>
            </el-col>
            <el-col :sm="4">
              <el-button @click="handleAddUploadItem">增加属性</el-button>
            </el-col>
          </el-row>
          <el-row
            v-for="(item, idx) in udList"
            :key="idx"
            :style="{display: 'flex', alignItems: 'center', marginTop: '15px'}"
          >
            <el-col :sm="4">
              <el-input v-model="item.attrName" @change="handleNameChange($event, idx)"/>
            </el-col>
            <el-col :sm="4" :offset="1">
              <el-input v-model="item.attrValue" @change="handleValueChange($event, idx)"/>
            </el-col>
            <el-col :sm="4" :offset="1">
              <div>
                <img width="60" v-if="item" :src="item.url" alt>&nbsp;
              </div>
            </el-col>
            <el-col :sm="8">
              <el-upload
                :style="{display: 'inline-block', marginRight: '10px'}"
                class="upload-demo"
                action="http://up-as0.qiniup.com/"
                :data="uploadData"
                :show-file-list="false"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                :on-change="((item) => {getSelectIdx(item,idx)})"
                :on-success="uploadSuccess"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button size="small" type="primary">上传图片</el-button>
              </el-upload>
              <el-button :style="{display: 'inline-block'}" @click="handleDelUploadItem(idx)">删除属性</el-button>
            </el-col>
            <!-- <el-col :sm="4">
              <el-button @click="handleDelUploadItem(idx)">删除属性</el-button>
            </el-col>-->
          </el-row>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">{{$t('common.cancel')}}</el-button>
        <el-button type="primary" @click="confirmEdit">{{$t('common.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tablefilter from "../components/table/commonTableFilter";
import commonTable from "../components/table/commonTable";
import uploadImg from "../components/uploadImg";
import { mapState } from "vuex";
import axios from "axios";

export default {
  name: "productList",
  components: {
    commonTable,
    uploadImg,
    Tablefilter
  },
  data() {
    let validateCountryId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("product.countryIdSelectTip")));
      } else {
        callback();
      }
    };
    let validateLink = (rule, value, callback) => {
      if (this.productForm.link1 === "" && this.productForm.link2 === "") {
        callback(new Error(this.$t("product.linkTip")));
      } else {
        callback();
      }
    };
    let validateImg = (rule, value, callback) => {
      if (this.productForm.productImg === "") {
        callback(new Error(this.$t("product.productImgTip")));
      } else {
        callback();
      }
    };
    return {
      uploadData: {
        token: "",
        key: ""
      },
      imgFile: {
        url: ""
      },
      udList: [],
      selectIdx: -1,
      columns: [
        {
          label: this.$t("common.operate"),
          prop: "operate",
          render: this.render("operate"),
          width: 200,
          tooltip: false
        },
        { type: "selection", width: 55 },
        { type: "expand", width: 40, render: this.render("expand") },
        { label: this.$t("common.id"), prop: "productId", width: 60 },
        {
          label: this.$t("common.country"),
          prop: "countryId",
          render: this.render("countryId")
        },
        { label: this.$t("common.customs"), prop: "hsCode" },
        { label: this.$t("common.productName"), prop: "productName" },
        { label: this.$t("common.expressName"), prop: "expressName" },
        {
          label: this.$t("common.productType"),
          prop: "productType",
          render: this.render("productType")
        },
        {
          label: this.$t("common.productImg"),
          prop: "productImg",
          render: this.render("productImg"),
          width: 90,
          tooltip: false
        },
        {
          label: this.$t("common.buyLink"),
          prop: "",
          render: this.render("link"),
          width: 100,
          tooltip: false
        },
        { label: this.$t("common.optimizer"), prop: "userName" },
        { label: this.$t("common.createTime"), prop: "uploadTime" }
      ],
      refresh: false,
      filterModel: {
        id: {
          label: this.$t("common.id"),
          value: ""
        },
        name: {
          label: this.$t("common.name"),
          value: ""
        },
        type: {
          label: this.$t("common.productType"),
          value: "",
          options: []
        },
        creator: {
          label: this.$t("common.optimizer"),
          value: ""
        },
        time: {
          label: this.$t("common.time"),
          value: "",
          time: true
        },
        country: {
          label: this.$t("common.country"),
          value: "",
          options: []
        }
      },
      filter: {},
      selectRow: [],
      editDialog: false,
      productForm: {
        productId: "",
        countryId: "",
        hsCode: "123432",
        productName: "",
        expressName: "",
        productType: "",
        productImg: "",
        // productAttr: "",
        link1: "",
        link2: ""
      },
      productFormRules: {
        countryId: [{ validator: validateCountryId, trigger: "blur" }],
        hsCode: [
          {
            required: true,
            message: this.$t("product.hsCodeTip"),
            trigger: "blur"
          }
        ],
        productName: [
          {
            required: true,
            message: this.$t("product.productNameTip"),
            trigger: "blur"
          }
        ],
        expressName: [
          {
            required: true,
            message: this.$t("product.expressNameTip"),
            trigger: "blur"
          }
        ],
        productType: [
          {
            required: true,
            message: this.$t("product.productTypeTip"),
            trigger: "blur"
          }
        ],
        productAttr: [
          {
            required: false,
            message: this.$t("product.productAttrTip"),
            trigger: "blur"
          }
        ],
        productImg: [{ validator: validateImg, trigger: "blur" }],
        link1: [{ validator: validateLink, trigger: "blur" }],
        link2: [{ validator: validateLink, trigger: "blur" }]
      },
      uploadList: []
    };
  },
  methods: {
    handleNameChange(val, idx) {
      this.udList[idx].attrName = val ? val.trim() : val;
      console.log(this.udList);
    },
    handleValueChange(val, idx) {
      this.udList[idx].attrValue = val ? val.trim() : val;
    },
    handleAddUploadItem() {
      this.udList.push({ attrName: "", url: "" });
    },
    handleDelUploadItem(idx) { 
      this.udList.splice(idx, 1);
    },
    async getToken(filename, idx) {
      const res = await axios.post(
        "http://111.230.194.39:8081/php/controller.php?action=getToken", 
        { key: filename },
        {
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret +=
                  encodeURIComponent(it) +
                  "=" +
                  encodeURIComponent(data[it]) +
                  "&";
              }
              return ret;
            }
          ],
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        }
      );
      console.log(res);

      this.uploadData.token = res.token;
      this.uploadData.key = filename;
    },
    async beforeUpload(file) {
      let path =
          "cod/source/" +
          (this.getStore("IP")
            ? this.getStore("IP").replace(/(.*\/\/)/, "")
            : location.hostname.replace(/(.*\/\/)/, "") + "/"),
        time = "mmdd",
        randNumber = (((1 + Math.random()) * 0x10000) | 0)
          .toString(16)
          .substring(1),
        now = new Date(),
        filename =
          path +
          new Date().Format(time) +
          "/" +
          Date.parse(now) +
          randNumber +
          "." +
          file.name.replace(/(.*\.)/, "");
      await this.getToken(filename);
    },
    getSelectIdx(item,idx) {
        console.log(idx);
      this.selectIdx = idx;
    },
    uploadSuccess(res) {
      res = res ? res : {};
      console.log(...arguments);
      if(this.selectIdx !== -1) this.udList[this.selectIdx].url = res.url || "";
    },
    render(prop) {
      let render = {};
      let _this = this;
      if (!prop) return;
      render.operate = (h, params) => {
        return h("div", [
          h(
            "el-button",
            {
              props: {
                type: "warning",
                size: "mini"
              },
              style: {
                marginLeft: "5px"
              },
              on: {
                click: () => {
                  this.editProduct(params.row);
                }
              }
            },
            this.$t("common.edit")
          ),
          h(
            "el-button",
            {
              props: {
                type: "danger",
                size: "mini"
              },
              style: {
                marginLeft: "5px"
              },
              on: {
                click: () => {
                  this.delProduct(params.row.productId);
                }
              }
            },
            this.$t("common.del")
          )
        ]);
      };
      render.link = (h, params) => {
        return h("div", [
          h(
            "a",
            {
              style: {
                marginLeft: "5px"
              },
              attrs: {
                href: params.row.link1,
                target: "_blank"
              }
            },
            this.$t("common.link1")
          ),
          h(
            "a",
            {
              style: {
                marginLeft: "5px"
              },
              attrs: {
                href: params.row.link2,
                target: "_blank"
              }
            },
            this.$t("common.link2")
          )
        ]);
      };
      render.productType = (h, params) => {
        return h(
          "div",
          _this.$t(
            "option." + _this.productTypeOptions[params.row.productType].label
          )
        );
      };
      render.countryId = (h, params) => {
        return h(
          "div",
          _this.$t(
            "option." +
              _this.countryOptions.filter(v => {
                return v.value == params.row.countryId;
              })[0].label
          )
        );
      };
      render.expand = (h, params) => {
        let item = [],
          properties = params.row.properties,
          column = ["property", "wareHouseName", "storageCounts"];
        column.forEach(v => {
          item.push(
            h("el-table-column", {
              props: {
                prop: v,
                label: v,
                border: true
              }
            })
          );
        });
        return h(
          "el-table",
          {
            props: {
              "data ": properties
            },
            class: {
              "el-table--border": true
            }
          },
          item
        );
      };
      render.productImg = (h, params) => {
        return h(
          "div",
          {
            class: {
              tableImg: true
            },
            on: {
              mouseover: e => {
                // e.toElement.parentElement.classList.add("enlarge");
                // e.toElement.parentElement.parentElement.classList.add("tableImgCell");
                // e.toElement.classList.add("enlarge");
              },
              mouseout: e => {
                // e.srcElement.parentElement.classList.remove('enlarge')
                // e.srcElement.parentElement.parentElement.classList.remove('tableImgCell')
                // e.srcElement.classList.remove('enlarge')
              }
            }
          },
          [
            h("img", {
              attrs: {
                src: params.row.productImg
              },
              class: {
                tableImg: true
              }
            })
          ]
        );
      };
      return render[prop];
    },
    getTableList() {
      return this.$productList;
    },
    search(filter) {
      this.filter = filter;
      this.refresh = true;
    },
    delProduct(Id) {
      let params = Id
        ? [Id]
        : this.selectRow.map(v => {
            return v.productId;
          });
      this.$delProduct(params).then(response => {
        if (response.code === "success") {
          this.$message.success(this.$t("common.delSuccess"));
          this.refresh = true;
          this.selectRow = [];
        } else {
          this.$message.error(this.$t("common.delError"));
        }
      });
    },
    editProduct(data) {
      this.editDialog = true;
      if (data) {
        for (let [k, v] of Object.entries(data)) {
          if (this.productForm.hasOwnProperty(k)) {
            this.productForm[k] = v;
          }
        }
        this.uploadList = [
          {
            url: data.productImg,
            name: data.productImg.replace(/(.*\/)/, ""),
            status: 1,
            percentage: 100
          }
        ];
        // this.formProductAttr2();
        this.udList = this.parseAttrData(data.productAttr);
      }
    },
    cancelEdit() {
      this.editDialog = false;
      this.resetForm();
    },
    resetForm() {
      this.$refs.productForm.resetFields();
      this.$refs.productForm.clearValidate();
      this.uploadList = [];
      this.udList = [];
      this.selectIdx = -1;
    },
    parseAttrData(cc) {
        let data = JSON.parse(cc), list = [];
        data.forEach((a)=> {
            let temp = new Object({}), arr = [];
            temp.attrName = a.attrName;
            // for(let i = 0; i<a.attrValue.length; i++) {
            //                     temp.attrValue = a.attrValue[i];
            //     temp.url = a.url[i];
            //     list.push(temp);
            // }
            a.attrValue.forEach((b,idx) => {
                temp.attrValue = b;
                temp.url = a.url[idx];
                list.push(Object.assign({},temp));
            })
        })
        console.log(list);
        return list;
    },
    formatlAttrData() {
      let attrList = [],
        uniqueObj = {};
      const { countryId, productId } = this.productForm;
      console.log(this.udList);
      this.udList.forEach(a => {
        let tempObj = {
          countryId,
          productId: productId || 0,
          attrName: a.attrName,
          attrValue: [],
          url: []
        };
        this.udList.forEach(b => {
          console.log(!uniqueObj[a.attrName]);
          if (!uniqueObj[a.attrName] && a.attrName === b.attrName) {
            tempObj.attrValue.push(b.attrValue);
            tempObj.url.push(b.url);
          }
        });
        if (tempObj.attrValue.length > 0 && tempObj.url.length > 0)
          attrList.push(tempObj);
        uniqueObj[a.attrName] = 1;
      });
      console.log(attrList);
      return attrList;
    },
    confirmEdit() {
      if (!this.editCheck("productForm")) return;
      //   this.formProductAttr();
      let params = {};
      params = Object.assign({}, this.productForm);
      if (!params.productId) delete params.productId;
      try {
        // params.productAttr = JSON.stringify(JSON.parse(params.productAttr));
        params.productAttr = JSON.stringify(this.formatlAttrData());
      } catch (e) {}
      this.$addProduct([params]).then(response => {
        if (response.code && response.code === "success") {
          params.productId
            ? this.$message.success(this.$t("common.editSuccess"))
            : this.$message.success(this.$t("common.addSuccess"));
          this.editDialog = false;
          this.refresh = true;
        } else {
          this.$message.error(this.$t("common.error"));
        }
      });
    },
    editCheck(ref) {
      let valid = true;
      this.$refs[ref].validate(v => {
        valid = v;
      });
      return valid;
    },
    formProductAttr() {
      let data = this.productForm.productAttr.trim();
      let row = [];
      let attrs = {};
      if (data === "") {
        this.productForm.productAttr = "";
        return;
      }
      row = data.split("\n");
      for (let i = 0; i < row.length; i++) {
        attrs[row[i].split(/[:：]/)[0]] = row[i]
          .split(/[:：]/)[1]
          .split(/[,，]+/);
      }
      this.productForm.productAttr = JSON.stringify(attrs);
    },
    formProductAttr2() {
      if (this.productForm.productAttr.replace(/[\s,，]+/, "") === "") {
        this.productForm.productAttr = "";
        return;
      }
      let data = JSON.parse(this.productForm.productAttr);
      let after = "";
      for (let [k, v] of Object.entries(data)) {
        after = after + k + ":" + v.join(",") + "\n";
      }
      this.productForm.productAttr = after;
    }
  },
  mounted() {
    console.log(this.userInfo);
    this.filterModel.country.options = this.countryOptions;
    this.filterModel.type.options = this.productTypeOptions;
  },
  computed: {
    ...mapState(["countryOptions", "productTypeOptions", "userInfo"])
  },
  watch: {
    uploadList: {
      handler(newV, oldV) {
        if (!newV || !newV.length) {
          return;
        }
        this.productForm.productImg = newV[0] && newV[0].url ? newV[0].url : "";
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>